package cn.cvs.servlet.sysUser;

import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysUserService;
import cn.cvs.util.SpringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@MultipartConfig
@WebServlet(name = "AddServlet", urlPatterns = "/sys/user/add")
public class AddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding ( "utf-8" );
        response.setContentType ( "text/html;charset=UTF-8" );
        SysUserService sysUserService= (SysUserService) SpringUtil.getBean ( "sysUserService" );

        String account = request.getParameter ( "account" );
        String realName = request.getParameter ( "realName" );
        String password = request.getParameter ( "password" );
        int sex = Integer.parseInt ( request.getParameter ( "sex" )!=null?request.getParameter ( "sex" ):"1" );
        String birthday = request.getParameter ( "birthday" );
        String phone = request.getParameter ( "phone" );
        String address = request.getParameter ( "address" );
        int roleId = Integer.parseInt ( request.getParameter ( "roleId" )!=null?request.getParameter ( "roleId" ):"3" );

        SysUser user=new SysUser ();
        user.setAccount ( account );
        user.setRealName ( realName );
        user.setPhone(phone);
        user.setRoleId(roleId);
        user.setSex ( sex );
        user.setPassword ( password );
        try {
            user.setBirthday (new SimpleDateFormat ("yyyy-MM-dd").parse ( birthday ) );
            user.setCreatedTime ( new Date (  ) );
            SysUser userSession = (SysUser) request.getSession ( ).getAttribute ( "userSession" );
            user.setCreatedUserId ( userSession.getId () );
        } catch (ParseException e) {
            request.getRequestDispatcher ( "/sys/user/toAdd" ).forward ( request,response );
        }
        user.setAddress ( address );

        int row = sysUserService.addUser ( user );
        if (row>0){
            request.getRequestDispatcher("/sys/user/list").forward(request,response);
        }else {
            request.getRequestDispatcher("/sys/user/ToAdd").forward(request,response);
        }
    }
}
